﻿using IMModel.Domain;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using IMModel.Domain.Common;
using System.Data.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using IMModel;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace IMTests
{
    /// <summary>
    /// Импорт данных анкетирования и успеваемости
    ///</summary>
    [TestClass()]
    public class TestSetAnket
    {
        static bool Compare(string fio, Respondent r)
        {
            var p = r.Person;
            //var f = fio.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (!fio.StartsWith(p.LastName)) return false;
            return fio.Contains(" " + p.FirstName[0]) && fio.Contains(" " + p.Patronymic[0]);
        }

        [TestMethod()]
        public void ImportAnket()
        {
            using (var ctx = new IMDataDataContext("Data Source=ugtudb;Initial Catalog=IndexMark;Integrated Security=True"))
            {
                var term = ctx.Terms.Single(x => x.IDTerm == 10);
                var opros = term.CharacteristicTerms.Single(x => x.Characteristic.Name ==
                    "Результаты анкетирования студентов (по данным университетской системы социомониторинга)");
                
                var dn = DateTime.Now.AddDays(-1);

                //// удаление ошибочных данных
                ////--------------------------
                //var v = opros.Answers.Where(x => x.DateTime.Value > dn).ToArray();
                //MessageBox.Show(v.Count().ToString());
                //foreach (var a in v)
                //{
                //    foreach (var g in a.GradationsAnswers)
                //        ctx.GradationsAnswers.DeleteOnSubmit(g);
                //    a.GradationsAnswers.Clear();
                //    opros.Answers.Remove(a);
                //    ctx.Answers.DeleteOnSubmit(a);
                //    a.IDCharacteristicTerm = 0;
                //}
                //ctx.SubmitChanges();

                //return;
                ////--------------------------

                OpenFileDialog od = new OpenFileDialog();
                if (od.ShowDialog() == DialogResult.OK)
                {
                    var f = od.OpenFile();
                    StreamReader sr = new StreamReader(f, Encoding.Default);
                    var s = sr.ReadToEnd();
                    var l = s.Split(new char[] { '\n', '\r' },
                        StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split('\t'));

                    var resps = term.Respondents.ToList();
                    var answs = l.ToList();

                    var gVosp = term.GradationTerms.Single(x =>
                        x.Gradation.Name == "воспитательный");
                    var gProf = term.GradationTerms.Single(x =>
                        x.Gradation.Name == "профессиональный");

                    var sProf = l.Average(x => double.Parse(x[2])) / 2 + 50;
                    var sVosp = l.Average(x => double.Parse(x[3])) / 2 + 50;

                    int no = 0, more_1 = 0;

                    foreach (var resp in term.Respondents)
                    {
                        var pw = answs.Where(x => Compare(x[0], resp));
                        double xProf = sProf;
                        double xVosp = sVosp;

                        var count = pw.Count();

                        if (count == 1)
                        {
                            var p = pw.First();
                            answs.Remove(p);
                            resps.Remove(resp);

                            xProf = double.Parse(p[2]) / 2 + 50;
                            xVosp = double.Parse(p[3]) / 2 + 50;
                        }

                        if (count == 0) ++no;
                        if (count > 1) ++more_1;

                        #region добавляем
                        // профессиональный
                        var a1 = new Answer()
                        {
                            IDCharacteristicTerm = opros.IDCharacteristicTerm,
                            DateTime = dn,
                            IDRespondent = resp.IDRespondent,
                            UserName = "k",
                            Volume = xProf,
                            IsDeleted = false,
                            IDOldAnswer = null,
                        };
                        var ga1 = new GradationsAnswer()
                        {
                            Answer = a1,
                            IDGradationTerm = gProf.IDGradationTerm,
                            //Volume = 1
                        };
                        //resp.Answers.Add(a1);
                        //a1.GradationsAnswers.Add(ga1);
                        //gVosp.GradationsAnswers.Add(ga1); 

                        ctx.Answers.InsertOnSubmit(a1);
                        ctx.GradationsAnswers.InsertOnSubmit(ga1);

                        // воспитательный
                        var a2 = new Answer()
                        {
                            IDCharacteristicTerm = opros.IDCharacteristicTerm,
                            DateTime = dn,
                            IDRespondent = resp.IDRespondent,
                            UserName = "k",
                            Volume = xVosp,
                            IsDeleted = false,
                            IDOldAnswer = null,
                        };
                        var ga2 = new GradationsAnswer()
                        {
                            Answer = a2,
                            IDGradationTerm = gVosp.IDGradationTerm,
                            //Volume = 1
                        };

                        ctx.Answers.InsertOnSubmit(a2);
                        ctx.GradationsAnswers.InsertOnSubmit(ga2);
                        #endregion
                    }

                    // списки не найденных в файлы
                    File.WriteAllText(
                        od.FileName + " - лишние ответы.txt",
                        answs.Count + "\n\r" +
                        string.Join("\n\r", answs.Select(x => x[0])));
                    File.WriteAllText(
                        od.FileName + " - лишние респонденты.txt",
                        resps.Count + "\n\r" +
                        string.Join("\n\r", resps.Select(x => x.Person.FullName)));
                    MessageBox.Show("Не найдено соответствий: " + no
                        + "Найдено > 1 соответствия:" + more_1);
                }

                //Console.WriteLine("k  " + string.Join(", ", k.Respondents));


                ////tr.Answers.AddRange(kr.Answers);
                ////foreach (var item in kr.Answers)
                ////{
                ////    item.IDRespondent = tr.IDRespondent;
                ////    item.Respondent = tr;
                ////}
                ////kr.Answers.Clear();
                ctx.SubmitChanges();


                //Console.WriteLine(kr);
                //Console.WriteLine(tr);

                //Console.WriteLine(ctx.Terms.Single(x => x.IDTerm == 8).CalcIndexes());
            }
        }

        public static void ImportAnketUspevaemostj(string s, int IDTerm)
        {
            using (var ctx = new IMDataDataContext("Data Source=ugtudb;Initial Catalog=IndexMark;Integrated Security=True"))
            {
                var term = ctx.Terms.Single(x => x.IDTerm == IDTerm);
                var opros = term.CharacteristicTerms.Single(x => x.Characteristic.Name ==
                    "Успеваемость студентов ");
                var dn = DateTime.Now;

                var l = s.Split(new char[] { '\n', '\r' },
                    StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split('\t'));

                var resps = term.Respondents.ToList();
                var answs = l.ToList();

                var gAbs = term.GradationTerms.Single(x =>
                    x.Gradation.Name == "абсолютная");
                var gKach = term.GradationTerms.Single(x =>
                    x.Gradation.Name == "качественная");

                var sAbs = AvgZnach(l, 1);
                var sKach = AvgZnach(l, 2);

                int no = 0, more_1 = 0;

                foreach (var resp in term.Respondents)
                {
                    double d = 0;
                    var pw = resp.Answers.Where(x => x.CharacteristicTerm == opros);
                    try
                    {
                    var ab = pw.Single(x => x.GradationsAnswers.Any(g => g.GradationTerm == gAbs));
                    var ka = pw.Single(x => x.GradationsAnswers.Any(g => g.GradationTerm == gKach));
                    d = ab.Volume;
                    ab.Volume = ka.Volume;
                    ka.Volume = d;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(resp.Person.FullName + " - "+ e.Message);
                    }
                }

                //foreach (var resp in term.Respondents)
                //{
                //    var pw = answs.Where(x => Compare(x[0], resp));
                //    float xAbs = sAbs;
                //    float xKach = sKach;

                //    var count = pw.Count();

                //    if (count == 1)
                //    {
                //        var p = pw.First();
                //        answs.Remove(p);
                //        resps.Remove(resp);

                //        float.TryParse(p[1], NumberStyles.Float, CultureInfo.InvariantCulture, out xAbs);
                //        float.TryParse(p[2], NumberStyles.Float, CultureInfo.InvariantCulture, out xKach);
                //        Console.WriteLine(xAbs + " 1 " + xKach);
                //    }

                //    if (count == 0)
                //    {
                //        ++no;
                //        Console.WriteLine(xAbs + " 0 " + xKach);
                //    }
                //    if (count > 1)
                //    {
                //        ++more_1;
                //        xAbs = AvgZnach(pw, 1);
                //        xKach = AvgZnach(pw, 2);
                //        resps.Remove(resp);
                //        //foreach (var p in pw.ToArray())
                //        //{
                //        //    answs.Remove(p);
                //        //}
                //        Console.WriteLine(xAbs + " n " + xKach);
                //    }

                //    #region добавляем
                //    // Абс. Успев-ть
                //    var a1 = new Answer()
                //    {
                //        IDCharacteristicTerm = opros.IDCharacteristicTerm,
                //        DateTime = dn,
                //        IDRespondent = resp.IDRespondent,
                //        UserName = "k",
                //        Volume = xAbs,
                //        IsDeleted = false,
                //        IDOldAnswer = null,
                //    };
                //    var ga1 = new GradationsAnswer()
                //    {
                //        Answer = a1,
                //        IDGradationTerm = gAbs.IDGradationTerm,
                //        Volume = 1
                //    };
                    
                //    ctx.Answers.InsertOnSubmit(a1);
                //    ctx.GradationsAnswers.InsertOnSubmit(ga1);

                //    // Кач. Успев-ть
                //    var a2 = new Answer()
                //    {
                //        IDCharacteristicTerm = opros.IDCharacteristicTerm,
                //        DateTime = dn,
                //        IDRespondent = resp.IDRespondent,
                //        UserName = "k",
                //        Volume = xKach,
                //        IsDeleted = false,
                //        IDOldAnswer = null,
                //    };
                //    var ga2 = new GradationsAnswer()
                //    {
                //        Answer = a2,
                //        IDGradationTerm = gKach.IDGradationTerm,
                //        Volume = 1
                //    };

                //    ctx.Answers.InsertOnSubmit(a2);
                //    ctx.GradationsAnswers.InsertOnSubmit(ga2);
                //    #endregion
                //}

                // списки не найденных в файлы
                Console.WriteLine("\n\rЛишние ответы:");
                Console.WriteLine(string.Join("\n\r", answs.Select(x => x[0])));
                Console.WriteLine("\n\rЛишние респонденты:");
                Console.WriteLine(string.Join("\n\r", resps.Select(x => x.Person.FullName)));
                //MessageBox.Show("Не найдено соответствий: " + no
                //    + "Найдено > 1 соответствия:" + more_1);

                ctx.SubmitChanges();
            }
        }

        private static float AvgZnach(IEnumerable<string[]> l, int pos)
        {
            float sProf = 0;
            foreach (var x in l)
            {
                try
                {
                    float f = 0;
                    float.TryParse(x[pos], NumberStyles.Float, CultureInfo.InvariantCulture, out f);
                    if (f > 0) sProf += f;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            sProf /= l.Count();
            return sProf;
        }

        //[TestMethod()]
        //public void Replace()
        //{
        //    using (var ctx = new IMDataDataContext("Data Source=ugtudb;Initial Catalog=IndexMark;Integrated Security=True"))
        //    {
        //        var term = ctx.Terms.Single(x => x.IDTerm == 6);
        //        //var context = term.GetIndexContextDoctors();
        //        var k = ctx.Persons.Where(x => x.LastName == "Тимохова").First();
        //        //&& x.FirstName == "Валерия" && x.Patronymic == "Александровна")
        //        var t = ctx.Persons.Where(x => x.LastName.Contains("(Тимохова")).First();
        //        //&& x.FirstName == "Валерия" && x.Patronymic == "Александровна"

        //        var kr = k.Respondents.Where(x => x.Term.IDTerm == 8).First();
        //        var tr = t.Respondents.Where(x => x.Term.IDTerm == 8).First();
        //        ////kr.
        //        ////Console.WriteLine(k +"   "+ t);//string.Join(", " , r));
        //        ////Console.WriteLine(string.Join(", ", t.Respondents));
        //        Console.WriteLine("k  " + string.Join(", ", k.Respondents));
        //        Console.WriteLine("ks  " + string.Join(", ", kr.Subscribes));
        //        Console.WriteLine("ka  " + string.Join(", ", kr.Answers));
        //        Console.WriteLine();
        //        Console.WriteLine("t  " + string.Join(", ", t.Respondents));
        //        Console.WriteLine("ts  " + string.Join(", ", tr.Subscribes));
        //        Console.WriteLine("ta  " + string.Join(", ", tr.Answers));

        //        ////tr.Answers.AddRange(kr.Answers);
        //        ////foreach (var item in kr.Answers)
        //        ////{
        //        ////    item.IDRespondent = tr.IDRespondent;
        //        ////    item.Respondent = tr;
        //        ////}
        //        ////kr.Answers.Clear();
        //        ////ctx.SubmitChanges();


        //        //Console.WriteLine(kr);
        //        //Console.WriteLine(tr);

        //        //Console.WriteLine(ctx.Terms.Single(x => x.IDTerm == 8).CalcIndexes());
        //    }
        //}
    }
}